package com.xukang.qd.client;

import com.ibm.mq.*;


import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 链接器操作发送
 */

public class ProducerIbmMqUtil {

    public static Logger logger= LoggerFactory.getLogger(ProducerIbmMqUtil.class);


    private  String userID ;
    private  String password ;
    // ip
    private String hostname ;
    //服务器连接通道
    private String channel;
    // MQ端口
    private int port;
    //服务器MQ服务使用的编码1381代表GBK、1208代表UTF
    private int CCSID;
    // 队列管理器
    private String queueManagerName;
    // 队列名
    private String queueName ;




    /**
     *
     * @param requestStr
     * @return
     */
    public String sendRequest(String requestStr) {
        MQQueue queue = null;
        MQQueueManager mqMgr= null;
        String messageId = "fail";
        try {
            logger.info("调用写入请求消息队列方法");
            //设置 队列管理器序号
            mqMgr = new MQQueueManager(queueManagerName);

            int openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SET_IDENTITY_CONTEXT;
            /**
             * 关闭了就重新打开,public bool isConnected()―――返回队列管理器是否在连接状态
             */
            if (mqMgr == null || !mqMgr.isConnected()) {
                mqMgr = new MQQueueManager(queueManagerName);
            }
            queue = mqMgr.accessQueue(queueName, openOptions);

            //第一步：设置写入消息的属性
            MQPutMessageOptions pmo = new MQPutMessageOptions();
            pmo.options = pmo.options + MQC.MQPMO_NEW_MSG_ID;
            pmo.options = pmo.options + MQC.MQPMO_SYNCPOINT;
            pmo.options = pmo.options + MQC.MQPMO_SET_IDENTITY_CONTEXT;
            //第二部：定义消息写入缓冲区
            MQMessage putMessage = new MQMessage();

            putMessage.userId = userID;
            //将数据放入消息缓冲区
            putMessage.write(requestStr.getBytes("GBK"));
            //第三步：将消息写入队列
            queue.put(putMessage, pmo);
            //第四步：提交
            mqMgr.commit();
            //第五步：返回生成的messageId
            messageId =Hex.encodeHexString(putMessage.messageId);
            logger.info("messageId:"+ messageId);
            queue.close();
            //断开队列管理器的连接
            mqMgr.disconnect();

        } catch (Exception e) {
            logger.error("mq队列queueManagerName："+queueManagerName+",queueName:"+queueName+"发生异常：{}",e);
        }finally {
            try {
                queue.close();
                //断开队列管理器的连接
                mqMgr.disconnect();
            } catch (MQException e1) {
                logger.error("关闭连接发生异常：{}",e1);
            }
        }
        return messageId;
    }
    public void sendResp(String requestStr, String messageId) {
        MQQueue queue = null;
        MQQueueManager mqMgr= null;
        try {
            logger.info("调用写入响应消息队列方法");

            //设置 队列管理器序号
             mqMgr = new MQQueueManager(queueManagerName);

            int openOptions = MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_SET_IDENTITY_CONTEXT;
            /**
             * 关闭了就重新打开,public bool isConnected()―――返回队列管理器是否在连接状态
             */
            if (mqMgr == null || !mqMgr.isConnected()) {
                mqMgr = new MQQueueManager(queueManagerName);
            }
             queue = mqMgr.accessQueue(queueName, openOptions);

            //第一步：设置写入消息的属性
            MQPutMessageOptions pmo = new MQPutMessageOptions();
            pmo.options = pmo.options + MQC.MQPMO_NEW_MSG_ID;
            pmo.options = pmo.options + MQC.MQPMO_SYNCPOINT;
            pmo.options = pmo.options + MQC.MQPMO_SET_IDENTITY_CONTEXT;
            //第二部：定义消息写入缓冲区
            MQMessage putMessage = new MQMessage();
            // 定义指定的messageId 放到 响应队列的 correlationId
            putMessage.correlationId =Hex.decodeHex(messageId.toCharArray());// messageId.getBytes("GBK"); // ？？？？
            putMessage.userId = userID;
            //将数据放入消息缓冲区
            putMessage.write(requestStr.getBytes("GBK"));
            //第三步：将消息写入队列
            queue.put(putMessage, pmo);
            //第四步：提交
            mqMgr.commit();
            //第四步：保存messageID,在接收MQ消息的时候设置correlationId为messageId
            queue.close();
            //断开队列管理器的连接
            mqMgr.disconnect();
        } catch (Exception e) {
            logger.error("mq队列queueManagerName："+queueManagerName+",queueName:"+queueName+"发生异常：{}",e);

        }finally {
            try {
                queue.close();
                //断开队列管理器的连接
                mqMgr.disconnect();
            } catch (MQException e1) {
                logger.error("关闭连接发生异常：{}",e1);
            }
        }
    }

    public  String getUserID() {
        return userID;
    }

    public String getHostname() {
        return hostname;
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public String getChannel() {
        return channel;
    }

    public void setChannel(String channel) {
        this.channel = channel;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getCCSID() {
        return CCSID;
    }

    public void setCCSID(int CCSID) {
        this.CCSID = CCSID;
    }

    public String getQueueManagerName() {
        return queueManagerName;
    }

    public void setQueueManagerName(String queueManagerName) {
        this.queueManagerName = queueManagerName;
    }

    public String getQueueName() {
        return queueName;
    }

    public void setQueueName(String queueName) {

        this.queueName = queueName;
    }

    public ProducerIbmMqUtil() {
    }
    public void init(){
        //MQ服务器的IP地址
        MQEnvironment.hostname = hostname;
        //通道类型:服务器连接通道
        MQEnvironment.channel = channel;
        //MQ端口
        MQEnvironment.port = port;
        //服务器MQ服务使用的编码1381代表GBK、1208代表UTF(Coded Character Set Identifier:CCSID)
        MQEnvironment.CCSID = CCSID;
        MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY,
                MQC.TRANSPORT_MQSERIES_CLIENT);
        logger.info("初始化队列" + queueName);
    }

}
